package com.esil.project;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.esil.project.util.FileUploadUtil;
import com.esil.project.util.RemplissageBDD;

/**
 * Classe d'upload de fichier par interface Web (non fonctionnelle)
 * 
 * @author Romain
 * 
 */
public class Upload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			FileUploadException, Exception {

		// Check that we have a file upload request
		if (ServletFileUpload.isMultipartContent(request)) {

			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			factory.setSizeThreshold(1000000);
			factory.setRepository(new File("upload-images"));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint
			upload.setSizeMax(1000000);

			// Parse the request
			List /* FileItem */items = upload.parseRequest(request);

			// // Process the uploaded items
			Iterator iter = items.iterator();
			String fileName="";
			String motscle="";
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				
							
				if (item.isFormField()) {
					//System.out.println("Descripteur : " + item.getString());
					motscle=item.getString();
				} else {
					fileName = item.getName();
					File parent = new File(getServletContext().getRealPath("/"));
					
					if (!new File(parent, "uploaded-images").exists())
						new File(parent, "uploaded-images").mkdirs();
					File uploadedFile = new File(parent + "/uploaded-images/"
							+ fileName);
			
					
					item.write(uploadedFile);
					PrintWriter out = response.getWriter();
						
					out.println("<script type='text/javascript'>alert('Fichier upload&eacute; !'); </script>");
				}
			}
			
			
			//Enregistrement dans le dossier images du WebContent puis dans la BDD
			String chemin=getServletContext().getRealPath("/");
			FileUploadUtil fup=new FileUploadUtil();
			fup.Save(chemin,fileName,motscle);

			
			
			response.sendRedirect("index.jsp");
		}

	}

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (ServletException ex) {
			ex.printStackTrace();
		} catch (FileUploadException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		try {
			processRequest(req, res);
		} catch (ServletException ex) {
			ex.printStackTrace();
		} catch (FileUploadException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
